<template>
	<div class="app-container">
		<el-form
			:model="queryParams"
			ref="queryRef"
			:inline="true"
			v-show="showSearch"
			label-width="100px"
		>
			<el-form-item label="班组名称" prop="teamName">
				<el-input
					v-model="queryParams.teamName"
					placeholder="请输入班组名称"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="关联班次" prop="shiftIds" style="width: 300px">
				<el-select
					v-model="queryParams.shiftIds"
					placeholder="请选择关联班次（可多选）"
					multiple
					clearable
					style="width: 100%"
					@change="handleShiftSearchChange"
				>
					<el-option
						v-for="period in periodList"
						:key="period.id"
						:label="period.periodName"
						:value="period.id"
					/>
				</el-select>
			</el-form-item>
			<el-form-item label="班组负责人" prop="leaderUserId" style="width: 300px">
				<el-select
					v-model="queryParams.leaderUserId"
					placeholder="请选择班组负责人"
					clearable
					style="width: 100%"
				>
					<el-option
						v-for="user in userList"
						:key="user.id"
						:label="user.name"
						:value="user.id"
					/>
				</el-select>
			</el-form-item>
			<el-form-item label="状态" prop="status" style="width: 240px">
				<el-select
					v-model="queryParams.status"
					placeholder="请选择状态"
					clearable
					style="width: 100%"
				>
					<el-option label="启用" value="1" />
					<el-option label="禁用" value="0" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery"
					>搜索</el-button
				>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					plain
					icon="Plus"
					@click="handleAdd"
					v-hasPermi="['web:team:add']"
					>新增</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="success"
					plain
					icon="Edit"
					:disabled="single"
					@click="handleUpdate"
					v-hasPermi="['web:team:edit']"
					>修改</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="danger"
					plain
					icon="Delete"
					:disabled="multiple"
					@click="handleDelete"
					v-hasPermi="['web:team:remove']"
					>删除</el-button
				>
			</el-col>
			<right-toolbar
				v-model:showSearch="showSearch"
				@queryTable="getList"
			></right-toolbar>
		</el-row>

		<el-table
			v-loading="loading"
			:data="teamList"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="班组名称" align="center" prop="teamName" />
			<el-table-column label="关联班次" align="center">
				<template #default="scope">
					<el-tag
						v-for="name in getShiftNames(scope.row.shiftIds)"
						:key="name"
						class="mr-1"
						type="info"
					>
						{{ name }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="班组负责人" align="center">
				<template #default="scope">
					{{ getUserNameById(scope.row.leaderUserId) }}
				</template>
			</el-table-column>
			<el-table-column label="班组成员" align="center">
				<template #default="scope">
					<el-tag
						v-for="name in getMemberNames(scope.row.memberIds)"
						:key="name"
						class="mr-1"
					>
						{{ name }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="班组描述" align="center" prop="teamDesc" />
			<el-table-column label="状态" align="center">
				<template #default="scope">
					<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
						{{ scope.row.status === 1 ? "启用" : "禁用" }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column
				label="操作"
				align="center"
				class-name="small-padding fixed-width"
			>
				<template #default="scope">
					<el-button
						link
						type="primary"
						icon="Edit"
						@click="handleUpdate(scope.row)"
						v-hasPermi="['web:team:edit']"
						>修改</el-button
					>
					<el-button
						link
						type="primary"
						icon="Delete"
						@click="handleDelete(scope.row)"
						v-hasPermi="['web:team:remove']"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改生产班组信息对话框 -->
		<el-dialog
			:title="title"
			v-model="open"
			width="500px"
			append-to-body
			@close="handleDialogClose"
		>
			<el-form ref="teamRef" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="班组名称" prop="teamName">
					<el-input v-model="form.teamName" placeholder="请输入班组名称" />
				</el-form-item>
				<!-- 关联班次：修复回显和删除bug -->
				<el-form-item label="关联班次" prop="shiftIds">
					<el-select
						v-model="form.shiftIds"
						placeholder="请选择关联班次（可多选）"
						multiple
						style="width: 100%"
						@change="handleShiftChange"
					>
						<el-option
							v-for="period in periodList"
							:key="period.id"
							:label="period.periodName"
							:value="period.id"
						/>
					</el-select>
				</el-form-item>
				<!-- 班组负责人 -->
				<el-form-item label="班组负责人" prop="leaderUserId">
					<el-select
						v-model="form.leaderUserId"
						placeholder="请选择班组负责人"
						style="width: 100%"
					>
						<el-option
							v-for="user in userList"
							:key="user.id"
							:label="user.name"
							:value="user.id"
						/>
					</el-select>
				</el-form-item>
				<!-- 班组成员 -->
				<el-form-item label="班组成员" prop="memberIds">
					<el-select
						v-model="form.memberIds"
						placeholder="请选择班组成员（可多选）"
						multiple
						style="width: 100%"
					>
						<el-option
							v-for="user in userList"
							:key="user.id"
							:label="user.name"
							:value="user.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="班组描述" prop="teamDesc">
					<el-input
						v-model="form.teamDesc"
						type="textarea"
						placeholder="请输入内容"
					/>
				</el-form-item>
				<!-- 状态选择 -->
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="form.status">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="Team">
	import { ref, reactive, toRefs, getCurrentInstance, onMounted } from "vue";
	import {
		listTeam,
		getTeam,
		delTeam,
		addTeam,
		updateTeam,
		getUserList,
	} from "@/api/prod_operate/sys_setting/prod_run/team_manage";
	import { listPeriod } from "@/api/prod_operate/sys_setting/prod_run/shift_manage";
	const { proxy } = getCurrentInstance();

	// 基础数据列表
	const userList = ref([]);
	const periodList = ref([]); // 班次列表（一次性加载，避免重复累积）
	const teamList = ref([]);

	// 状态管理
	const open = ref(false);
	const loading = ref(true);
	const showSearch = ref(true);
	const ids = ref([]);
	const single = ref(true);
	const multiple = ref(true);
	const total = ref(0);
	const title = ref("");

	const data = reactive({
		form: {
			status: 1,
			shiftIds: [], // 始终用数组存储，避免字符串类型问题
			memberIds: [],
		},
		queryParams: {
			pageNum: 1,
			pageSize: 10,
			teamName: null,
			shiftIds: [], // 搜索用班次ID数组
			leaderUserId: null,
			status: null,
		},
		rules: {
			teamName: [
				{ required: true, message: "班组名称不能为空", trigger: "blur" },
			],
			shiftIds: [
				{
					required: true,
					message: "请选择至少一个关联班次",
					trigger: "change",
				},
			],
			leaderUserId: [
				{ required: true, message: "请选择班组负责人", trigger: "change" },
			],
			memberIds: [
				{
					required: true,
					message: "请选择至少一名班组成员",
					trigger: "change",
				},
			],
			status: [{ required: true, message: "请选择状态", trigger: "change" }],
		},
	});

	const { queryParams, form, rules } = toRefs(data);
	// 新增：弹窗关闭时的处理（关键修复）
	function handleDialogClose() {
		resetFormData(); // 专门用于清空表单数据的方法
	}
	// 表单重置（重构为专门清空数据的方法）
	function resetFormData() {
		form.value = {
			teamId: null,
			teamName: null,
			shiftIds: [], // 强制清空关联班次数据
			leaderUserId: null,
			memberIds: [],
			teamDesc: null,
			status: 1,
			createTime: null,
		};
		// 重置表单验证状态
		if (proxy.$refs["teamRef"]) {
			proxy.$refs["teamRef"].resetFields();
		}
	}
	// 页面初始化：只加载一次班次数据，避免重复累积
	onMounted(() => {
		fetchUserList();
		if (periodList.value.length === 0) {
			// 防止重复加载导致选项累积
			fetchPeriodList();
		}
		getList();
	});

	/** 获取用户列表 */
	function fetchUserList() {
		getUserList().then((response) => {
			if (response.code === 200) {
				userList.value = response.data;
			}
		});
	}

	/** 获取班次列表（关键：只加载一次，避免选项重复） */
	function fetchPeriodList() {
		listPeriod({ pageNum: 1, pageSize: 100 }).then((response) => {
			if (response.code === 200) {
				// 深拷贝避免引用问题，同时去重（根据id）
				const newPeriods = response.rows.filter(
					(newItem) =>
						!periodList.value.some((oldItem) => oldItem.id === newItem.id)
				);
				periodList.value = [...periodList.value, ...newPeriods];
			}
		});
	}

	/** 班次选择变化时处理（修复删除bug） */
	function handleShiftChange(ids) {
		// 确保始终是数组类型，避免null或undefined
		form.value.shiftIds = ids || [];
	}

	/** 搜索班次变化时处理 */
	function handleShiftSearchChange(ids) {
		queryParams.value.shiftIds = ids || [];
	}

	/** 根据ID获取用户名 */
	function getUserNameById(userId) {
		if (!userId) return "";
		const user = userList.value.find((item) => item.id == userId);
		return user ? user.name : "未知用户";
	}

	/** 根据成员ID字符串获取成员名称列表 */
	function getMemberNames(memberIds) {
		if (!memberIds) return [];
		const idArr = memberIds.split(",").filter((id) => id); // 过滤空值
		return idArr.map((id) => {
			const user = userList.value.find((item) => item.id == id);
			return user ? user.name : `未知用户(${id})`;
		});
	}

	/** 根据班次ID字符串获取班次名称列表 */
	function getShiftNames(shiftIds) {
		if (!shiftIds) return [];
		const idArr = shiftIds.split(",").filter((id) => id); // 过滤空值
		return idArr.map((id) => {
			const period = periodList.value.find((item) => item.id == id);
			return period ? period.periodName : `未知班次(${id})`;
		});
	}

	/** 查询生产班组信息列表 */
	function getList() {
		loading.value = true;
		// 处理搜索参数：数组转字符串
		const params = { ...queryParams.value };
		params.shiftIds =
			params.shiftIds.length > 0 ? params.shiftIds.join(",") : null;
		listTeam(params).then((response) => {
			teamList.value = response.rows;
			total.value = response.total;
			loading.value = false;
		});
	}

	// 取消按钮
	function cancel() {
		open.value = false;
		reset();
	}

	// 表单重置（关键：强制清空数组）
	function reset() {
		form.value = {
			teamId: null,
			teamName: null,
			shiftIds: [], // 强制空数组
			leaderUserId: null,
			memberIds: [], // 强制空数组
			teamDesc: null,
			status: 1,
			createTime: null,
		};
		proxy.resetForm("teamRef");
	}

	/** 搜索按钮操作 */
	function handleQuery() {
		queryParams.value.pageNum = 1;
		getList();
	}

	/** 重置按钮操作 */
	function resetQuery() {
		proxy.resetForm("queryRef");
		// 手动重置多选数组
		queryParams.value.shiftIds = [];
		queryParams.value.leaderUserId = null;
		queryParams.value.status = null;
		handleQuery();
	}

	// 多选框选中数据
	function handleSelectionChange(selection) {
		ids.value = selection.map((item) => item.teamId);
		single.value = selection.length != 1;
		multiple.value = !selection.length;
	}

	/** 新增按钮操作 */
	function handleAdd() {
		reset();
		open.value = true;
		title.value = "添加生产班组信息";
	}

	/** 修改按钮操作（修复回显逻辑） */
	function handleUpdate(row) {
		reset(); // 先重置清空
		const _teamId = row.teamId || ids.value;
		getTeam(_teamId).then((response) => {
			const teamData = response.data;
			// 处理关联班次：字符串转数组（关键：过滤空值+转数字）
			teamData.shiftIds = teamData.shiftIds
				? teamData.shiftIds
						.split(",")
						.filter((id) => id)
						.map(Number)
				: [];

			// 处理班组成员
			teamData.memberIds = teamData.memberIds
				? teamData.memberIds
						.split(",")
						.filter((id) => id)
						.map(Number)
				: [];

			// 处理负责人ID
			teamData.leaderUserId = teamData.leaderUserId
				? Number(teamData.leaderUserId)
				: null;

			// 赋值到表单
			form.value = { ...teamData };
			open.value = true;
			title.value = "修改生产班组信息";
		});
	}

	/** 提交按钮 */
	function submitForm() {
		proxy.$refs["teamRef"].validate((valid) => {
			if (valid) {
				const submitForm = { ...form.value };
				// 数组转字符串（过滤空值）
				submitForm.shiftIds = submitForm.shiftIds.filter((id) => id).join(",");
				submitForm.memberIds = submitForm.memberIds
					.filter((id) => id)
					.join(",");

				if (submitForm.teamId != null) {
					updateTeam(submitForm).then((response) => {
						proxy.$modal.msgSuccess("修改成功");
						open.value = false;
						getList();
					});
				} else {
					addTeam(submitForm).then((response) => {
						proxy.$modal.msgSuccess("新增成功");
						open.value = false;
						getList();
					});
				}
			}
		});
	}

	/** 删除按钮操作 */
	function handleDelete(row) {
		const _teamIds = row.teamId || ids.value;
		proxy.$modal
			.confirm(`是否确认删除生产班组信息编号为"${_teamIds}"的数据项？`)
			.then(function () {
				return delTeam(_teamIds);
			})
			.then(() => {
				getList();
				proxy.$modal.msgSuccess("删除成功");
			})
			.catch(() => {});
	}

	// 初始化查询
	getList();
</script>

<style scoped>
	.mr-1 {
		margin-right: 8px;
	}
	.block {
		display: block;
	}
	.mt-1 {
		margin-top: 8px;
	}
</style>
